package com.sa.token.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sa.token.dto.request.system.ExportLoginLogRequest;
import com.sa.token.dto.request.system.LoginLogRequest;
import com.sa.token.entity.SysLoginLogEntity;
import com.sa.token.mapper.SysLoginLogMapper;
import com.sa.token.message.Result;
import com.sa.token.message.StandardResponse;
import com.sa.token.service.SysLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * <p>
 * 登录日志表 服务实现类
 * </p>
 *
 * @author xhs
 * @since 2021-12-29
 */
@Slf4j
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLogEntity> implements SysLoginLogService {

    /**
     * 查询登录日志
     *
     * @return
     */
    @Override
    public StandardResponse<Object> getLoginLog(LoginLogRequest logRequest) {
        Page page = new Page<>(logRequest.getCurrent(), logRequest.getSize());
        LambdaQueryWrapper<SysLoginLogEntity> queryWrapper = getSysLoginLogEntity(logRequest);
        Page list = getBaseMapper().selectPage(page, queryWrapper);
        return StandardResponse.build(Result.QUERY_SUCCESS).setData(list);
    }


    /**
     * 导出登录日志
     *
     * @param logRequest
     */
    @Override
    public void exportLoginLog(ExportLoginLogRequest logRequest, HttpServletResponse response) {
        // 数据拷贝
        LoginLogRequest request = new LoginLogRequest();
        BeanUtils.copyProperties(logRequest, request);
        // 查询数据
        LambdaQueryWrapper<SysLoginLogEntity> wrapper = getSysLoginLogEntity(request);
        List<SysLoginLogEntity> logList = getBaseMapper().selectList(wrapper);
        log.info("登录数据:{}条", logList.size());
        // 创建excel并填充入数据
        handleExcel(response, logList);
    }

    /**
     * 按条件查询数据
     *
     * @param logRequest
     * @return
     */
    private LambdaQueryWrapper<SysLoginLogEntity> getSysLoginLogEntity(LoginLogRequest logRequest) {
        return new QueryWrapper<SysLoginLogEntity>().lambda()
                .like(StringUtils.hasLength(logRequest.getLoginId()), SysLoginLogEntity::getLoginId, logRequest.getLoginId())
                .like(StringUtils.hasLength(logRequest.getLoginIp()), SysLoginLogEntity::getCreatorIp, logRequest.getLoginIp())
                .eq(StringUtils.hasLength(logRequest.getStatus()), SysLoginLogEntity::getStatus, logRequest.getStatus())
                .ge(StringUtils.hasLength(logRequest.getStartTime()), SysLoginLogEntity::getCreateTime, logRequest.getStartTime())
                .le(StringUtils.hasLength(logRequest.getEndTime()), SysLoginLogEntity::getCreateTime, logRequest.getEndTime())
                .orderByDesc(SysLoginLogEntity::getCreateTime);
    }

    /**
     * 创建excel并填充入数据
     *
     * @param logList
     */
    private void handleExcel(HttpServletResponse response, List<SysLoginLogEntity> logList) {
        log.info("导出Excel");
        try {
            // 创建工作簿
            Workbook wb = WorkbookFactory.create(true);
            // 创建工作表
            Sheet sheet = wb.createSheet("登录日志");
            // 设置列宽
            for (int i = 0; i < 9; i++) {
                sheet.setColumnWidth(i, 26 * 256);
            }
            // 创建行(索引从0开始)
            Row row = sheet.createRow(0);
            // 设置行高
            row.setHeightInPoints(20.25f);
            // 设置表头样式
            CellStyle cellHeadStyle = setCellHeadStyle(wb);
            // 设置数据样式
            CellStyle style = setCellStyle(wb);

            Cell cell = null;
            cell = row.createCell(0);
            cell.setCellValue("编号");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(1);
            cell.setCellValue("登录账号");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(2);
            cell.setCellValue("登录IP");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(3);
            cell.setCellValue("登录地点");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(4);
            cell.setCellValue("浏览器");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(5);
            cell.setCellValue("操作系统");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(6);
            cell.setCellValue("登录状态");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(7);
            cell.setCellValue("操作信息");
            cell.setCellStyle(cellHeadStyle);

            cell = row.createCell(8);
            cell.setCellValue("创建时间");
            cell.setCellStyle(cellHeadStyle);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

            // 填充数据
            int rowNum = 1;
            for (SysLoginLogEntity logEntity : logList) {
                // 创建行(索引从1开始)
                Row sheetRow = sheet.createRow(rowNum);
                Cell cell1 = null;
                cell1 = sheetRow.createCell(0);
                cell1.setCellValue(logEntity.getId());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(1);
                cell1.setCellValue(logEntity.getLoginId());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(2);
                cell1.setCellValue(logEntity.getCreatorIp());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(3);
                cell1.setCellValue(logEntity.getCreatorAddress());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(4);
                cell1.setCellValue(logEntity.getBrowser());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(5);
                cell1.setCellValue(logEntity.getOperatingSystem());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(6);
                if ("1".equals(logEntity.getStatus())) {
                    cell1.setCellValue("成功");
                } else {
                    cell1.setCellValue("失败");
                }
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(7);
                cell1.setCellValue(logEntity.getMessage());
                cell1.setCellStyle(style);

                cell1 = sheetRow.createCell(8);
                cell1.setCellValue(dateFormat.format(logEntity.getCreateTime()));
                cell1.setCellStyle(style);

                rowNum = rowNum + 1;
            }
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("登录日志.xlsx", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            // 释放资源
            outputStream.close();
            wb.close();
            log.info("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建excel并填充入数据异常:{},>>>", e.getMessage());
        }
    }

    /**
     * 设置表头样式
     *
     * @param wb
     * @return
     */
    private CellStyle setCellHeadStyle(Workbook wb) {
        // 设置样式
        // 创建单元格样式对象
        CellStyle cellStyle = wb.createCellStyle();
        // 横向居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 纵向居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 下边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        // 左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        // 上边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        // 右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        // 背景颜色
        cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    /**
     * 设置数据样式
     *
     * @param wb
     * @return
     */
    private CellStyle setCellStyle(Workbook wb) {
        // 设置样式
        // 创建单元格样式对象
        CellStyle cellStyle = wb.createCellStyle();
        // 横向居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 纵向居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //下边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        //左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        //上边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        //右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        //设置自动换行
        cellStyle.setWrapText(true);
        return cellStyle;
    }
}
